package springboot.configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.DeleteDbFiles;
import studio.raptor.ddal.common.util.StringUtil;

/**
 * 功能描述
 *
 * @author Charley
 * @since 1.0
 */
public class H2Starter {

  private static final String PATH = "~";
  private static final String DB = "db";
  private static final String URL = String.format("jdbc:h2:%s/%s;FILE_LOCK=SOCKET", PATH, DB);
  private static final String USER = "root";
  private static final String PASSWORD = "123";
  private static final String[] DB_FILE = new String[]{"/sql/data.sql"};

  public static void initialize(){
    try {
      DeleteDbFiles.execute(PATH, DB, false);
      BufferedReader[] bufferedReaders = new BufferedReader[DB_FILE.length];
      try (
          Connection connection = tryToGetConnection();
          Statement statement = connection.createStatement()
      ) {
        for (int i = 0; i < DB_FILE.length; i++) {
          bufferedReaders[i] = new BufferedReader(
              new InputStreamReader(H2Starter.class.getResourceAsStream(DB_FILE[i]),
                  "utf-8"));
        }
        for (BufferedReader bufferedReader : bufferedReaders) {
          String sqlLine;
          while (null != (sqlLine = bufferedReader.readLine())) {
            if (!StringUtil.isEmpty(sqlLine) && !sqlLine.trim().startsWith("--")) {
              statement.execute(sqlLine);
            }
          }
        }

      } finally {
        for (BufferedReader bufferedReader : bufferedReaders) {
          bufferedReader.close();
        }
      }
    }catch (SQLException | IOException e){
      e.printStackTrace();
    }
  }

  private static Connection tryToGetConnection() throws SQLException {
    return DriverManager.getConnection(URL, USER, PASSWORD);
  }
}
